package com.appcenter.application.service;

import com.appcenter.application.dto.orgs.OrgDto;
import com.appcenter.application.dto.orgusers.OrgUserDto;
import com.appcenter.application.dto.orgusers.ResultOrgUserDto;
import com.appcenter.application.dto.users.UserDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.org.GetOrgsInput;
import com.appcenter.application.input.orguser.*;
import com.appcenter.application.mapper.AppsMapper;
import com.appcenter.application.mapper.OrgUsersMapper;
import com.appcenter.application.mapper.OrgsMapper;
import com.appcenter.application.mapper.UsersMapper;
import com.appcenter.application.model.Apps;
import com.appcenter.application.model.OrgUsers;
import com.appcenter.application.model.Orgs;
import com.appcenter.application.model.Users;
import com.appcenter.application.output.orguser.*;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

import static org.apache.http.util.TextUtils.isBlank;

@Service
public class OrgUserService {
    @Autowired
    OrgsMapper orgsMapper;
    @Autowired
    AppsMapper appsMapper;
    @Autowired
    OrgUsersMapper orgUsersMapper;
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    OrgService orgService;
    @Autowired
    ObjectFinal objectFinal;

    /**
     *  创建人:Coke
     *  备注: 创建部门用户关系
     *  时间: 2019/4/26 13:56 
     *  参数: 
     */
    public CreateOrgUserOutput CreateOrgUser(CreateOrgUserInput input) throws Exception {
        CreateOrgUserOutput output = new CreateOrgUserOutput();


//        Example example = new Example(Users.class);
//        Example.Criteria criteriau = example.createCriteria();
//        criteriau.andEqualTo("userCode", input.getItem().getUserCode());
//
//        int userCount = usersMapper.selectByExample(example).size();
//        //int userCount=1;
//        Users user = null;
//        if (userCount > 0) {
//            //如果该用户与该部门已经有关系  则提示部门人员重复  阻止添加
//
//            Example exampleOrgUser = new Example(OrgUsers.class);
//            Example.Criteria criteria = exampleOrgUser.createCriteria();
//
//            if (input.getItem().getAppCode() == null) {
//                criteria.andIsNull("appCode");
//            } else {
//                criteria.andEqualTo("appCode", input.getItem().getAppCode());
//            }
//            criteria.andEqualTo("orgId", input.getItem().getOrgId());
//            criteria.andEqualTo("userCode", input.getItem().getUserCode());
//
//            int orgUserCount = orgUsersMapper.selectByExample(exampleOrgUser).size();
//            if (orgUserCount > 0) {
//
//                throw new ErrorJsonResult("1000031", "该部门已存在此用户信息");
//            } else {
//                user = usersMapper.getUsersByUserCode(input.getItem().getUserCode(),objectFinal.getDataEffectiveVersion());
//            }
//        } else {
//            throw new ErrorJsonResult("1000031", "用户账号不存在");
//        }
//        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//        OrgUsers orgUser = new OrgUsers();
//        orgUser.setId(uuid);
//        orgUser.setOrgId(input.getItem().getOrgId());
//        orgUser.setOrgCodePath(orgsMapper.selectByPrimaryKey(input.getItem().getOrgId()).getOrgCodePath());
//        orgUser.setUserId(user.getId());
//        orgUser.setUserCode(user.getUserCode());
//        orgUsersMapper.insertSelective(orgUser);
//
//        OrgUserDto item = new OrgUserDto();
//        ObjectUnit.Copy(orgUser,item);
//        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 删除部门成员信息
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public DeleteOrgUserOutput DeleteOrgUser(DeleteOrgUserInput input) {
        DeleteOrgUserOutput output = new DeleteOrgUserOutput();
        //
        //orgUsersMapper.deleteByPrimaryKey(input.getItem().getId());
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改部门用户关系
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public EditOrgUserOutput EditOrgUser(EditOrgUserInput input) throws Exception {
        EditOrgUserOutput output = new EditOrgUserOutput();

//        Users user = usersMapper.getUsersByUserCode(input.getItem().getUserCode(),objectFinal.getDataEffectiveVersion());
//        if (user == null) {
//            throw new ErrorJsonResult("1000031", "未找到用户信息");
//        }
//
//        OrgUsers orguser = orgUsersMapper.selectByPrimaryKey(input.getItem().getId());
//
//        if (orguser != null) {
//            orguser.setOrgId(input.getItem().getOrgId());
//            orguser.setOrgCodePath(orgsMapper.selectByPrimaryKey(input.getItem().getOrgId()).getOrgCodePath());
//            orguser.setUserId(user.getId());
//            orguser.setUserCode(user.getUserCode());
//            orgUsersMapper.updateByPrimaryKey(orguser);
//        }
//        OrgUserDto item = new OrgUserDto();
//        ObjectUnit.Copy(orguser,item);
//        output.setItem(item);
        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 获取部门用户信息
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */

    public GetOrgUsersOutput GetOrgUsers(GetOrgUsersInput input) throws Exception {
        GetOrgUsersOutput output = new GetOrgUsersOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        //input.setPenetrate(true);
        if (input.getAppCode() == null || input.getAppCode().length() == 0) {
            input.setAppCode(null);
        }
        if (input.getOrgId() != null) {
            Example exampleOrg = new Example(Orgs.class);
            Example.Criteria criteria = exampleOrg.createCriteria();
            criteria.andEqualTo("id", input.getOrgId());
            criteria.andEqualTo("versionNo", input.getVersionNo());
            Orgs org = orgsMapper.selectOneByExample(exampleOrg);
            input.setOrgCodePath(org.getOrgCodePath());
        }
        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "orgcodepath desc");
        //List<Apps> ls = AppMapper.SearchApps(input);
        List<ResultOrgUserDto> ls = orgUsersMapper.searchOrgUsers(input);
        PageInfo<ResultOrgUserDto> page = new PageInfo<>(ls);
        List<ResultOrgUserDto> orgUserList = page.getList();
        if (orgUserList != null && orgUserList.size() > 0) {
            for (int i = 0; i < orgUserList.size(); i++) {
                ResultOrgUserDto orguser = orgUserList.get(i);

                Example exampleUsers = new Example(Users.class);
                Example.Criteria criteria = exampleUsers.createCriteria();
                criteria.andEqualTo("id", orguser.getUserId());
                criteria.andEqualTo("versionNo",input.getVersionNo());
                Users u = usersMapper.selectOneByExample(exampleUsers);


                Example exampleOrg = new Example(Orgs.class);
                Example.Criteria criteriaorg = exampleOrg.createCriteria();
                criteriaorg.andEqualTo("id", orguser.getOrgId());
                criteriaorg.andEqualTo("versionNo",input.getVersionNo());
                Orgs o = orgsMapper.selectOneByExample(exampleOrg);

                if (u != null && o != null) {
                    orguser.setOrgId(o.getId());
                    orguser.setOrgName(o.getOrgName());
                    orguser.setUserCode(u.getUserCode());
                    orguser.setUserName(u.getUserName());
                    orguser.setEmail(u.getEmail());
                    orguser.setPhone(u.getPhone());
                    orguser.setSex(u.getSex());
                    orguser.setBirthday(u.getBirthday());
                    orguser.setOfficePhone(u.getOfficePhone());
                    orguser.setJobNumber(u.getJobNumber());
                    orguser.setCardNo(u.getCardNo());
                    orguser.setDingUserId(u.getDingUserId());
                    orguser.setUserId(u.getId());
                }
            }
        }
        BusinessLogger.Info(LoggerGenre.View, "获取部门对应人员信息", input);
        output.setItems(new PagedResult<ResultOrgUserDto>(orgUserList, (int) page.getTotal()));
        return output;
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 加载部门用户信息
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        try {
            PageLoadOutput output = new PageLoadOutput();
            Map<String, OrgDto> parentOrgDtoDic = new HashMap<String, OrgDto>();

            Example exampleApp = new Example(Apps.class);
            Example.Criteria criteria = exampleApp.createCriteria();
            criteria.andEqualTo("useHrOrg", false);
            List<Apps> apps = appsMapper.selectByExample(exampleApp);
            GetOrgsInput orgsInput=new GetOrgsInput();
            orgsInput.setAppCode(input.getAppCode());
            List<OrgDto> orgDtos =orgService.GetOrgs(orgsInput).getOrgs();
            GetOrgUsersOutput outputUser = this.GetOrgUsers(input);
            output.setApps(apps);
            output.setOrgs(orgDtos);
            output.setItems(outputUser.getItems());
            return output;
        } catch (Exception e) {
            throw new ErrorJsonResult("1010203123", e.toString());
        }
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 搜索部门用户信息
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public SearchOrgOutput SearchOrg(SearchOrgInput input) throws Exception {
        SearchOrgOutput output = new SearchOrgOutput();
        Long curversion=objectFinal.getDataEffectiveVersion();
        List<Orgs> orgs=orgService.getOrgs(null, input.getAppCode(), false,curversion,false);
        List<OrgDto> orgDtos = orgService.GetOrgTreeList(orgs);
        output.setOrgs(orgDtos);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 删除部门
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public DeleteOrgOutput DeleteOrg(DeleteOrgInput input) {
        DeleteOrgOutput output = new DeleteOrgOutput();

//        Orgs curOrg = orgsMapper.selectByPrimaryKey(input.getItem().getId());
//
//        Example exampleOrgChind = new Example(Orgs.class);
//        Example.Criteria criteriaOrgChind = exampleOrgChind.createCriteria();
//        criteriaOrgChind.andEqualTo("parentId", input.getItem().getId());
//        int countOrgChind = orgsMapper.selectByExample(exampleOrgChind).size();
//        if (countOrgChind > 0) {
//            throw new ErrorJsonResult("1000031", "有子组织机构，不能删除！");
//        }
//        Example exampleOrgUser = new Example(OrgUsers.class);
//        Example.Criteria criteriaOrgUser = exampleOrgUser.createCriteria();
//        criteriaOrgUser.andEqualTo("orgId", input.getItem().getId());
//        int countOrgUsers = orgUsersMapper.selectByExample(exampleOrgUser).size();
//        if (countOrgUsers > 0) {
//            throw new ErrorJsonResult("1000031", "有用户属于此组织机构，不能删除！");
//        }
//        orgsMapper.deleteByPrimaryKey(input.getItem().getId());
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 创建部门
     *  时间: 2019/4/26 13:57 
     *  参数: 
     */
    public CreateOrgOutput CreateOrg(CreateOrgInput input) throws Exception {
        CreateOrgOutput output = new CreateOrgOutput();

//        Example exampleOrg = new Example(Orgs.class);
//        Example.Criteria criteriaOrg = exampleOrg.createCriteria();
//        criteriaOrg.andEqualTo("orgCode", input.getItem().getOrgCode());
//        if(input.getItem().getAppCode()==null){
//            criteriaOrg.andIsNull("appCode");
//        }else{
//            criteriaOrg.andEqualTo("appCode", input.getItem().getAppCode());
//        }
//        int countOrg = orgsMapper.selectByExample(exampleOrg).size();
//        if (countOrg > 0) {
//            throw new ErrorJsonResult("1000031", "组织机构编号已存在！");
//        }
//        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//        Orgs org = new Orgs();
//        org.setId(uuid);
//        org.setAppCode(input.getItem().getAppCode());
//        org.setOrgCode(input.getItem().getOrgCode());
//        org.setOrgName(input.getItem().getOrgName());
//        org.setParentId(input.getItem().getParentId());
//
//        if (input.getItem().getParentId() == null || input.getItem().getParentId().length() == 0) {
//            org.setOrgIdPath(uuid);
//            org.setOrgCodePath(input.getItem().getOrgCode());
//            org.setOrgNamePath(input.getItem().getOrgName());
//            org.setLevel(1L);
//        } else {
//            Orgs parentOrg = orgsMapper.selectByPrimaryKey(input.getItem().getParentId());
//            org.setOrgIdPath(parentOrg.getOrgIdPath() + "/" + uuid);
//            org.setOrgCodePath(parentOrg.getOrgCodePath() + "/" + input.getItem().getOrgCode());
//            org.setOrgNamePath(parentOrg.getOrgNamePath() + "/" + input.getItem().getOrgName());
//            org.setLevel(parentOrg.getLevel() + 1);
//        }
//
//        if (input.getItem().getListOrder() == 0) {
//
//            Orgs maxListOrder = orgsMapper.maxListOrder(input.getItem().getParentId());
//            if (maxListOrder == null) {
//                org.setListOrder(10L);
//            } else {
//                org.setListOrder(maxListOrder.getListOrder() + 10);
//            }
//        }
//        orgsMapper.insertSelective(org);
//
//
//
//        OrgDto item = new OrgDto();
//        ObjectUnit.Copy(org,item);
//        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改部门
     *  时间: 2019/4/26 14:07
     *  参数: 
     */
    public EditOrgOutput EditOrg(EditOrgInput input) throws Exception {
        EditOrgOutput output = new EditOrgOutput();

        return output;
    }


}
